package gitobject;

import CommitLink.*;
import gitobject.Commit;
import repository.Repository;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

/**
 * @author shkstart
 * @create 2021-12-19 19:52
 */
public class Branch extends GitObject {
    //分支名
    private String name;
    //分支在版本库中的存放路径
    private String branchPath;
    //该分支最后一次提交的commit的hash值
    private String commitId;

    public Branch() {
    }

    public Branch(String name) throws Exception {
        this.name = name;
        this.branchPath = new File(".").getCanonicalPath() + File.separator+ ".jit" + File.separator + "refs" + File.separator + "heads" + File.separator + name;
        this.commitId = Commit.getLastCommit();
        Commit commit = new Commit();
        commit.setBranchName(name);
        FileOutputStream fos = null;
        File branch = new File(branchPath);
        branch.createNewFile();
        fos = new FileOutputStream(branch);
        fos.write(this.commitId.getBytes(StandardCharsets.UTF_8));
        fos.close();
    }

    public String getHead() throws IOException {
        File HEAD = new File(new File(".").getCanonicalPath() + File.separator+ ".jit" + File.separator + "HEAD");
        if (getValue(HEAD).length() == 0){
            return null;
        }
        String path = getValue(HEAD).substring(5).replace("\n", "");
        return new File(".").getCanonicalPath() + File.separator+ ".jit" + File.separator + path;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBranchPath() {
        return branchPath;
    }

    public void setBranchPath(String branchPath) {
        this.branchPath = branchPath;
    }

    public String getCommitId() {
        return commitId;
    }

    public void setCommitId(String commitId) {
        this.commitId = commitId;
    }


}
